package com.jm.springboot21.controller;

import com.jm.springboot21.pojo.Result;
import com.jm.springboot21.pojo.User;
import com.jm.springboot21.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin("*")
public class UserController {
    @Autowired
    private UserService userService;
    //显示当前用户
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        return Result.success(user);
    }

    // 登录接口
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public Result login(@RequestParam String username, @RequestParam String password) {
        Object loginResult = userService.login(username, password);
        if (loginResult != null) {
            // 假设loginResult是User对象
            User user = (User) loginResult;
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("token", "generated-token"); // 实际应该生成真实token
            resultData.put("userId", user.getId());
            resultData.put("user", user);
            return Result.success(resultData);
        } else {
            return Result.error("用户名或密码错误");
        }
    }
    // 注册接口
    @RequestMapping(value = "/register", method = {RequestMethod.GET, RequestMethod.POST})
    public Result register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public Result update(@RequestBody User user) {
        if (user.getId() ==0) {
            return Result.error("用户ID不能为空");
        }

        // 检查用户是否存在
        User existingUser = userService.findById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        boolean success = userService.update(user);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }
}

